package com.terry.androidkotlin.adapter

import android.animation.ObjectAnimator
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.terry.androidkotlin.R
import com.terry.androidkotlin.app.VApp
import common.base.BaseActivity
import common.base.VLog
import common.helper.SingleClickListener
import common.model.GlideRoundTransform
import common.utils.base.DipPixelUtils
import common.utils.base.GlideUtils
import common.utils.base.StringUtils
import common.utils.utilcode.util.ScreenUtils

/**
 * Author: Terry
 * bilibili: 码农安小辰
 * Github: https://gitee.com/itchenning/AndroidKotlin
 * Date: 2020-03-08 16:47
 * Comment:
 */
class QQMessageAdapter(val activity: BaseActivity) : RecyclerView.Adapter<QQMessageAdapter.ViewHoler>(), View.OnTouchListener, SingleClickListener {

    private var mLastX = 0F
    private var mLastY = 0F
    private var MAXX = 0F
    private var MINX = -DipPixelUtils.dip2px(80F) * 2F
    private var mLastSlidingView: View? = null
    private var mData = (0..99).toMutableList()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHoler {
        val view = View.inflate(VApp.get(), R.layout.item_qq_msg, null)
        val leftRoot = view.findViewById<View>(R.id.leftRootView)
        val leftParams = LinearLayout.LayoutParams(-2, -1)
        leftParams.width = ScreenUtils.getScreenWidth()
        leftRoot.layoutParams = leftParams
        val params = LinearLayout.LayoutParams(leftParams.width + Math.abs((MINX)).toInt(), DipPixelUtils.dip2px(50F))
        view.layoutParams = params
        return ViewHoler(view)
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onBindViewHolder(holder: ViewHoler, position: Int) {
        val item = mData.get(position)
        GlideUtils.showImage(activity.requestManager, holder.iconIv, R.mipmap.anxiaochen, GlideRoundTransform(DipPixelUtils.dip2px(30F)))
        holder.titleTv.text = "安小辰${item}"
        holder.subtitleTv.text = "你好啊你好啊${item}"
        holder.timeTv.text = genDate()
        holder.rootView.tag = position
        holder.topBtn.tag = item
        holder.deleteBtn.tag = item
        holder.rootView.setOnTouchListener(this)
        holder.topBtn.setOnClickListener(this)
        holder.deleteBtn.setOnClickListener(this)
        holder.rootView.translationX = 0F
    }

    private fun genDate(): String {
        val year = 2020
        val month = (Math.random() * 12 + 1).toInt()
        val date = (Math.random() * 28 + 1).toInt()
        return "${year}-${StringUtils.formatNum(month, 2)}-${StringUtils.formatNum(date, 2)}"
    }

    class ViewHoler(view: View) : RecyclerView.ViewHolder(view) {
        val iconIv = view.findViewById<ImageView>(R.id.iconIv)
        val titleTv = view.findViewById<TextView>(R.id.titleTv)
        val subtitleTv = view.findViewById<TextView>(R.id.subtitleTv)
        val timeTv = view.findViewById<TextView>(R.id.timeTv)
        val rootView = view.findViewById<View>(R.id.rootView)
        val topBtn = view.findViewById<View>(R.id.topBtn)
        val deleteBtn = view.findViewById<View>(R.id.deleteBtn)
    }

    override fun onTouch(v: View, event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                mLastX = event.rawX
                mLastY = event.rawY
                fixLast(v)
                v.parent.requestDisallowInterceptTouchEvent(isSliding(v))
            }
            MotionEvent.ACTION_MOVE -> {
                if (!canMove(v)) {
                    return true
                }
                val curX = event.rawX
                val curY = event.rawY
                val diffX = curX - mLastX
                val diffY = curY - mLastY
                mLastX = curX
                mLastY = curY
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    VLog.i("QQ", "左右滑")
                    slidingItem(diffX, v)
                    v.parent.requestDisallowInterceptTouchEvent(true)
                } else if (!isSliding(v)) {
                    VLog.i("QQ", "上下滑")
                    v.parent.requestDisallowInterceptTouchEvent(false)
                }
            }
            MotionEvent.ACTION_UP -> {
                fixSliding()
            }
        }
        return true
    }

    private fun canMove(v: View): Boolean {
        if (mLastSlidingView != null && mLastSlidingView != v && mLastSlidingView!!.translationX != 0F) {
            return false
        }
        return true
    }

    private fun isSliding(v: View): Boolean {
        if (mLastSlidingView != null && mLastSlidingView != v && mLastSlidingView!!.translationX != 0F) {
            VLog.i("QQ", "1")
            return true
        }
        if (v.translationX == MINX) {
            VLog.i("QQ", "2")
            return true
        }
        if (v.translationX == MAXX) {
            VLog.i("QQ", "3")
            return false
        }
        VLog.i("QQ", "4")
        return true
    }

    private fun fixLast(view: View) {
        if (mLastSlidingView != null && mLastSlidingView != view) {
            showLeft(mLastSlidingView!!)
        }
    }

    private fun fixSliding() {
        if (mLastSlidingView == null) {
            return
        }
        val curTransX = mLastSlidingView!!.translationX
        if (curTransX > MINX / 2) {
            showLeft(mLastSlidingView!!)
        } else {
            showRight(mLastSlidingView!!)
        }
    }

    private fun showRight(view: View) {
        val cur = view.translationX
        val anim = ObjectAnimator.ofFloat(view, "translationX", cur, MINX)
        anim.setDuration(Math.abs((cur - MINX)).toLong())
        anim.start()
    }

    private fun showLeft(view: View) {
        val cur = view.translationX
        val anim = ObjectAnimator.ofFloat(view, "translationX", cur, MAXX)
        anim.setDuration(Math.abs((cur - MAXX)).toLong())
        anim.start()
    }

    private fun slidingItem(diffX: Float, view: View) {
        fixLast(view)
        val transX = getInRangeX(view, diffX)
        view.translationX = transX
        if (mLastSlidingView == null) {
            mLastSlidingView = view
        } else if (mLastSlidingView!!.translationX == 0F) {
            mLastSlidingView = view
        }
    }

    private fun getInRangeX(view: View, diffX: Float): Float {
        var curTransX = view.translationX + diffX
        curTransX = Math.min(curTransX, MAXX)
        curTransX = Math.max(curTransX, MINX)
        return curTransX
    }

    override fun onSingleClick(view: View) {
        when (view.id) {
            R.id.topBtn -> switchToTop(view)
            R.id.deleteBtn -> deleteOne(view)
        }
    }

    private fun deleteOne(view: View) {
        val item = view.tag.toString().toInt()
        val index = mData.indexOf(item)
        mData.remove(item)
        notifyItemRemoved(index)
        mLastSlidingView = null
    }

    private fun switchToTop(view: View) {
        val item = view.tag.toString().toInt()
        val position = mData.indexOf(item)
        mData.remove(item)
        notifyItemRemoved(position)
        mData.add(0, item)
        notifyItemInserted(0)
        mLastSlidingView = null
    }
}